﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.Blo;
using Dict.DataModel;
using ProtoBuf.Message;

namespace UI
{
    public class TalentDetail : MonoBehaviour
    {
        public GameObject detailRoot;
        public GameObject detailPrefab1;    //2个值 小
        public GameObject detailPrefab2;    //1个值 小
        public GameObject detailPrefabBig1;    //2个值 大
        public GameObject detailPrefabBig2;    //1个值 大
        public GameObject costRoot;
        public GameObject labNamePrefab;
        public GameObject costItemRoot;
        public GameObject btnActive;
        public GameObject labActived;
        public GameObject commonIconPref;
        public UILabel labCostCoin;
        public UILabel labTalentDesc;
        public UISprite talentDescBg;

        public TalentPage talentPage;

        UITalent talentInfo;

        List<string> costHeroList = new List<string>();
        int costCoinNum;
        int costHeroNum;
        string costItemInfo = "";
        bool recieveClick = true;   //播特效过程中点击激活无效

        public void SetTalent(UITalent talent)
        {
            talentInfo = talent;
            bool actived = talent.isActived; //已解锁和未激活的 显示布局相同
            UIHero heroInfo = talent.owner;

            detailRoot.transform.DestroyChildren();

            int y = GetComponent<UIWidget>().height/2 - 38;
            GameObject pref1 = detailPrefab1;
            GameObject pref2 = detailPrefab2;
            if (actived || !talent.isUnlocked)
            {
                y -= 40;
                pref1 = detailPrefabBig1;
                pref2 = detailPrefabBig2;
            }

            string valueRight = "";

            //人物等级需要
            string color = "[c50000]";
            if (heroInfo.level >= talent.data.levelLimit)
                color = "[000000]";
            GameObject levelNeed = GetDetainItem(pref2, y);
            levelNeed.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("character_level_charge"),
                color + heroInfo.level.ToString() + "[/u][000000]/" + talent.data.levelLimit.ToString() + "[/u]", "");
            levelNeed.GetComponent<TalentDetailItem>().lineUp.SetActive(true);
            y -= levelNeed.GetComponent<UIWidget>().height;

            //激活天赋
            TableTalent talentData = DictTalentBlo.GetTableTalent(talent.data.talentId);
            string nameIndex = "tanlent";
            if (talentData != null)
                nameIndex = talentData.Name;
            GameObject talentUnlock = GetDetainItem(pref2, y);
            talentUnlock.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("active_talent"), "[000000]" + TableTextBlo.GetText(nameIndex) + "[/u]", "");

            //天赋描述
            y = GetComponent<UIWidget>().height / 2 - 84;
            if (actived || !talent.isUnlocked)
                y -= 50;
            string descIndex = "tanlent";
            if (talentData != null)
                descIndex = talentData.Desc;
            talentDescBg.gameObject.SetActive(true);
            labTalentDesc.text = TableTextBlo.GetText(descIndex);
            talentDescBg.transform.localPosition = new Vector3(talentDescBg.transform.localPosition.x, y, 0);
            y -= talentDescBg.height + talentUnlock.GetComponent<UIWidget>().height/2;
            y += 1;

            if (actived || !talent.isUnlocked)
                y -= 7;
            
            //进阶等级
            string valueLeft = heroInfo.talentLevel.ToString() + TableTextBlo.GetText("jie");
            valueRight = "";
            if (!actived && talent.IsTrunk)
                valueRight = talent.data.talentLevel + TableTextBlo.GetText("jie");
            if (!talent.IsTrunk)
                valueLeft = talent.data.talentLevel + TableTextBlo.GetText("jie");

            GameObject advanceLevel = GetDetainItem(pref1, y);
            advanceLevel.GetComponent<TalentDetailItem>().lineUp.SetActive(true);
            advanceLevel.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("level"), valueLeft, valueRight);
            y -= advanceLevel.GetComponent<UIWidget>().height;
            
            //进阶前后数值
            BaseAttributeData dataBefore = heroInfo.CurrentAttribute;
            BaseAttributeData dataAfter = BaseAttributeData.zero;
            if(!actived)
                heroInfo.GetTalentChangeAttribute(talent.data.talentLevel, out dataBefore, out dataAfter);
            
            //攻击
            valueRight = "";
            if (!actived)
                valueRight = dataAfter.GetProp(AttributeQueue.Attack).ToString(); 
            GameObject propertyAtt = GetDetainItem(pref1, y);
            propertyAtt.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("attack"), dataBefore.GetProp(AttributeQueue.Attack).ToString() , valueRight);
            y -= propertyAtt.GetComponent<UIWidget>().height;

            //生命
            valueRight = "";
            if (!actived)
                valueRight = dataAfter.GetProp(AttributeQueue.Hp).ToString();
            GameObject propertyHp = GetDetainItem(pref1, y);
            propertyHp.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("hp"), dataBefore.GetProp(AttributeQueue.Hp).ToString(), valueRight);
            y -= propertyHp.GetComponent<UIWidget>().height;

            //物防
            valueRight = "";
            if (!actived)
                valueRight = dataAfter.GetProp(AttributeQueue.PhyDefend).ToString();
            GameObject propertyPdef = GetDetainItem(pref1, y);
            propertyPdef.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("pdef"), dataBefore.GetProp(AttributeQueue.PhyDefend).ToString(), valueRight);
            y -= propertyPdef.GetComponent<UIWidget>().height;

            //法防
            valueRight = "";
            if (!actived)
                valueRight = dataAfter.GetProp(AttributeQueue.MagicDefend).ToString();
            GameObject propertyMdef = GetDetainItem(pref1, y);
            propertyMdef.GetComponent<TalentDetailItem>().SetValues(TableTextBlo.GetText("mdef"), dataBefore.GetProp(AttributeQueue.MagicDefend).ToString(), valueRight);
            y -= propertyMdef.GetComponent<UIWidget>().height;

            //进阶消耗
            if(actived || !talent.isUnlocked)
            {
                if (talent.isActived)
                    labActived.GetComponent<UILabel>().text = TableTextBlo.GetText("already_actived");
                else
                    labActived.GetComponent<UILabel>().text = TableTextBlo.GetText("not_actived");

                costRoot.SetActive(false);
                btnActive.SetActive(false);
                labActived.SetActive(true);
            }
            else
            {
                costCoinNum = 0;
                costHeroNum = 0;
                costItemInfo = "";
                if (costHeroList != null)
                    costHeroList.Clear();

                btnActive.SetActive(true);
                labActived.SetActive(false);
                costRoot.SetActive(true);
                costItemRoot.transform.DestroyChildren();
                string[] costIds = talent.Cost.Split(';');
                //float[] posx = { -75, 75 };
                string coinNum = "";
                List<GameObject> iconList = new List<GameObject>();
                for (int i = 0; i < costIds.Length; i++)
                {
                    string[] costinfo = costIds[i].Split(',');
                    if (costinfo[0].StartsWith(Dict.Config.TableConst.item))
                    {
                        costItemInfo = costIds[i];
                        long itemCount = StaticData.playerData.GetSimpleItemCount(costinfo[0]);
                        float scale = (float)85 / 90;
                        GameObject obj = AssetLoad.ResourceManager.Instance.LoadResource("prefab/ItemIcon") as GameObject;
                        GameObject icon = Instantiate(obj);
                        icon.GetComponent<ItemIcon>().SetItem(costinfo[0]);
                        icon.GetComponent<ItemIcon>().UpdateItemCount(itemCount.ToString() + "/" + costinfo[1], UIWidget.Pivot.Center);
                        icon.GetComponent<ItemIcon>().m_callback = OnCostItemClick;
                        icon.transform.parent = costItemRoot.transform;
                        icon.transform.localScale = new Vector3(scale, scale, scale);
                        iconList.Add(icon);

                        GameObject labname = Instantiate(labNamePrefab);
                        labname.SetActive(true);
                        labname.GetComponent<UILabel>().text = TableTextBlo.GetText("name_" + costinfo[0]);
                        labname.transform.parent = icon.transform;
                        labname.transform.localScale = Vector3.one;
                        labname.transform.localPosition = new Vector3(0, -57, 0);
                    }
                    if (costinfo[0].StartsWith(Dict.Config.TableConst.war))
                    {
                        costHeroList = StaticData.playerData.InstPlayerData.GetAdvenceAvailableHeroList(costinfo[0]);
                        float scale = (float)85 / 95;
                        GameObject obj = AssetLoad.ResourceManager.Instance.LoadResource("prefab/HeroIcon") as GameObject;
                        GameObject icon = Instantiate(obj);
                        icon.GetComponent<HeroIcon>().SetHeroWithId(costinfo[0]);
                        icon.GetComponent<HeroIcon>().UpdateItemCount(costHeroList.Count.ToString() + "/" + costinfo[1], UIWidget.Pivot.Center);
                        icon.GetComponent<HeroIcon>().m_callback = OnCostHeroClick;
                        icon.transform.parent = costItemRoot.transform;
                        icon.transform.localScale = new Vector3(scale, scale, scale);
                        iconList.Add(icon);

                        TableHero herodata = DictHeroBlo.GetTableHero(costinfo[0]);
                        GameObject labname = Instantiate(labNamePrefab);
                        labname.SetActive(true);
                        labname.GetComponent<UILabel>().text = TableTextBlo.GetText(herodata.name);
                        labname.transform.parent = icon.transform;
                        labname.transform.localScale = Vector3.one;
                        labname.transform.localPosition = new Vector3(0, -57, 0);

                        costHeroNum = int.Parse(costinfo[1]);
                    }
                    if (costinfo[0].StartsWith(Dict.Config.TableConst.coin))
                    {
                        costCoinNum = int.Parse(costinfo[1]);
                        coinNum = costinfo[1];
                    }
                }

                int x = costItemRoot.GetComponent<UIWidget>().width / (iconList.Count + 1) - costItemRoot.GetComponent<UIWidget>().width/2;
                foreach (var item in iconList)
                {
                    item.transform.localPosition = new Vector3(x, 8, 0);
                    x += costItemRoot.GetComponent<UIWidget>().width / (iconList.Count + 1);
                }

                labCostCoin.text = coinNum;
            }

            recieveClick = true;
        }

        void OnCostItemClick(string id)
        {
            CommonMethod.ShowDescription(UIItemType.Item, id);
        }

        void OnCostHeroClick(string id)
        {
            CommonMethod.ShowDescription(UIItemType.Hero, id);
        }

        public void OnActiveBtn()
        {
            if (!recieveClick)
                return;

            if (!string.IsNullOrEmpty(talentInfo.data.parent) && !talentInfo.owner.TalentData[talentInfo.data.parent].IsTrunk
                && !talentInfo.owner.TalentData[talentInfo.data.parent].isActived || !string.IsNullOrEmpty(talentInfo.data.parent2) 
                && !talentInfo.owner.TalentData[talentInfo.data.parent2].IsTrunk && !talentInfo.owner.TalentData[talentInfo.data.parent2].isActived)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("need_to_active_branch_talent_before"));
                return;
            }

            if (talentInfo.owner.level < talentInfo.data.levelLimit)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("role_level_lack"));
                return;
            }
            if (StaticData.playerData.coin < costCoinNum)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("coin_lack"));
                return;
            }
            if(costHeroList.Count < costHeroNum)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("active_material_lack"));
                return;
            }
            string itemid = "";
            long itemNum = 0;
            if(costItemInfo != "")
            {
                string[] info = costItemInfo.Split(',');
                itemid = info[0];
                itemNum = int.Parse(info[1]);
                if(StaticData.playerData.GetSimpleItemCount(itemid) < itemNum)
                {
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("active_material_lack"));
                    return;
                }
            }

            CSWarriorTalent msg = new CSWarriorTalent();
            msg.guid = talentInfo.owner.guid;
            msg.talent = talentInfo.data.talentLevel;

            if(costCoinNum > 0)
            {
                BaseResource res = new BaseResource();
                res.id = "coin";
                res.num = costCoinNum;
                msg.cost.Add(res);
            }

            if (costHeroNum > 0)
            {
                foreach(var item in costHeroList)
                {
                    BaseResource res = new BaseResource();
                    res.id = talentInfo.owner.heroId;
                    res.num = 1;
                    res.guid = item;
                    msg.cost.Add(res);
                }
            }

            if(costItemInfo != "")
            {
                BaseResource res = new BaseResource();
                res.id = itemid;
                res.num = (int)itemNum;
                msg.cost.Add(res);
            }

            NetAPI.SendHttp(OpDefine.CSWarriorTalent, msg, MsgCallback);
        }

        void MsgCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if(bSuccess)
            {
                SCWarriorTalent msg = packet.kBody as SCWarriorTalent;
                StaticData.playerData.Delete(msg.cost);
                StaticData.playerData.InstPlayerData.UpdateHero(msg.guid);

                recieveClick = false;
                talentPage.PlayActiveParticle();
            }
        }
        
        GameObject GetDetainItem(GameObject prefab,float y)
        {
            GameObject obj = Instantiate(prefab);
            obj.SetActive(true);
            obj.transform.parent = detailRoot.transform;
            obj.transform.localScale = Vector3.one;
            obj.transform.localPosition = new Vector3(0, y, 0);

            return obj;
        }
    }
}
